package com.iplant.basic.serviceImpl.dao.sfc;

import com.iplant.base.po.OutResult;
import com.iplant.base.po.ServiceResult;
import com.iplant.base.utils.annotation.dao.DBBaseDAO;
import com.iplant.base.utils.general.StringUtils;
import com.iplant.base.utils.sql.BaseDAO;
import com.iplant.basic.service.basicenum.sfc.SFCFileClassification;
import com.iplant.basic.service.po.bms.BMSEmployee;
import com.iplant.basic.service.po.sfc.SFCFile;
import com.iplant.basic.serviceImpl.dao.bfc.BFCSystemConfigDAO;
import com.iplant.basic.utils.Constants;
import lombok.extern.slf4j.Slf4j;

@DBBaseDAO(SFCFile.class)
@Slf4j
public class SFCFileDAO extends BaseDAO {

    private static SFCFileDAO Instance = null;

    public static SFCFileDAO getInstance() {
        if (Instance == null) {
            Instance = new SFCFileDAO();
        }
        return Instance;
    }

    public SFCFileDAO() {
        super("");
        this.Init();
    }

    /**
     * 根据网络路径获取实际物理路径（/iPlantAMS/upload/file/2024/03/21/3.处理详情_113623_b487fef2-fd8e-423a-ad5e-2a708d374ee4.png）
     */
    public ServiceResult<String> getFilePathByUrl(BMSEmployee wLoginUser, String fileUrl,
                                                  OutResult<Integer> wErrorCode) {
        ServiceResult<String> wResult = new ServiceResult<>();
        wResult.Result = "";
        try {
            //①获取config路径
            String staticPath = Constants.getStaticPath();
            //②截取项目
            int startIndex = fileUrl.indexOf("upload");
            if (startIndex != -1) {
                String desiredPath = fileUrl.substring(startIndex);
                //③拼接完整的文件路径
                wResult.Result = StringUtils.Format("{0}{1}", staticPath, desiredPath);
            } else {
                wResult.FaultCode += "The specified upload substring was not found.";
                return wResult;
            }
        } catch (Exception e) {
            wResult.FaultCode += e.toString();
            log.error(e.toString());
        }
        return wResult;
    }

    public ServiceResult<String> getFileSavePathByClassification(BMSEmployee wLoginUser, int fileClassification,
                                                                 OutResult<Integer> wErrorCode) {
        ServiceResult<String> wResult = new ServiceResult<>();
        wResult.Result = "";
        try {
            switch (SFCFileClassification.getEnumType(fileClassification)) {
                case Default:
                    break;
                case EquipmentInstruction://设备指导文件存储路径
                    wResult.Result = BFCSystemConfigDAO.getInstance().BFC_GetValueByName(wLoginUser, -1,
                            "EquipmentInstruction_Dir",
                            wErrorCode);
                    if (StringUtils.isEmpty(wResult.Result)) {
                        wResult.FaultCode += "系统参数[EquipmentInstruction_Dir]未配置!";
                        return wResult;
                    }
                    break;
                case OperationFlow://操作流程文件存储路径
                    wResult.Result = BFCSystemConfigDAO.getInstance().BFC_GetValueByName(wLoginUser, -1,
                            "OperationFlow_Dir",
                            wErrorCode);
                    if (StringUtils.isEmpty(wResult.Result)) {
                        wResult.FaultCode += "系统参数[OperationFlow_Dir]未配置!";
                        return wResult;
                    }
                    break;
                case Universal://通用性文件存储路径
                    wResult.Result = BFCSystemConfigDAO.getInstance().BFC_GetValueByName(wLoginUser, -1,
                            "Universal_Dir",
                            wErrorCode);
                    if (StringUtils.isEmpty(wResult.Result)) {
                        wResult.FaultCode += "系统参数[Universal_Dir]未配置!";
                        return wResult;
                    }
                    break;
                case Process://工艺文件存储路径
                    wResult.Result = BFCSystemConfigDAO.getInstance().BFC_GetValueByName(wLoginUser, -1,
                            "Process_Dir",
                            wErrorCode);
                    if (StringUtils.isEmpty(wResult.Result)) {
                        wResult.FaultCode += "系统参数[Process_Dir]未配置!";
                        return wResult;
                    }
                    break;
            }

            //判断文件路径是否存在，若不存在，则创建目录
            if (StringUtils.isNotEmpty(wResult.Result)) {
                java.io.File file = new java.io.File(wResult.Result);
                if (!file.exists()) {
                    file.mkdirs();
                }
            }
        } catch (Exception e) {
            wResult.FaultCode += e.toString();
            log.error(e.toString());
        }
        return wResult;
    }

    /**
     * 获取文件名称（/iPlantAMS/upload/file/2024/03/21/3.处理详情_113623_b487fef2-fd8e-423a-ad5e-2a708d374ee4.png）
     */
    public String getFileNameByUrl(BMSEmployee wLoginUser, String fileUrl, OutResult<Integer> wErrorCode) {
        String wResult = "";
        try {
            //①截取最后/部分
            int lastSlashIndex = fileUrl.lastIndexOf('/');
            String fileNameWithUnderscore = fileUrl.substring(lastSlashIndex + 1);
            //②截取后缀
            int lastDotIndex = fileNameWithUnderscore.lastIndexOf('.');
            String extension = fileNameWithUnderscore.substring(lastDotIndex);
            //③得到除后缀的部分
            String fileNameWithoutUnderscore = fileNameWithUnderscore.substring(0, lastDotIndex);
            //④剔除后40位字符
            String trimmedString = fileNameWithoutUnderscore.substring(0, fileNameWithoutUnderscore.length() - 44);
            //⑤拼接前缀+后缀
            wResult = StringUtils.Format("{0}{1}", trimmedString, extension);
        } catch (Exception ex) {
            log.error("getFileNameByUrl", ex);
        }
        return wResult;
    }
}
